package com.kira.scaffoldmvc.Interceptor;


import com.kira.scaffoldmvc.Utils.JwtUtil;
import com.kira.scaffoldmvc.Utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;

import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Allow-Credentials", "*");

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求放行");
            return true;
        }

        String token = request.getHeader("Authorization");
        if (token == null)
            return false;

        Map<String, Object> claims;
        try {
            claims = JwtUtil.parseToken(token);
        } catch (Exception e) {
            return false;//这个是JWT解析失败时我们不放行
        }
//把我们的部分用户消息放到我们的ThreadLocal里面
        ThreadLocalUtil.set(claims);
//放行
        return true;


    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        ThreadLocalUtil.remove();
    }
}
